#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL fa[maxn],a[maxn];
LL siz[maxn];
LL find(LL x){
    if(fa[x]!=x) return fa[x]=find(fa[x]);
    return fa[x];
}
LL merge(LL x,LL y){
    if(find(x)!=find(y)){
        siz[find(x)]+=siz[find(y)];
        fa[find(y)]=find(x);
    }
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n;cin>>n;
  for(LL i=1;i<=n;i++) fa[i]=i,siz[i]=1;
  for(LL i=1;i<=n;i++) cin>>a[i];
  for(LL i=1;i<=n;i++){
      LL to=a[i];
      merge(i,to);
  }
  LL maxv1=-1;LL maxv2=-2;LL pos1=0;LL pos2=0;
  for(LL i=1;i<=n;i++){
     if(fa[i]==i){
        if(siz[i]>maxv1){
            maxv2=maxv1;
            maxv1=siz[i];
            pos2=pos1;
            pos1=i;
        }
        else if(siz[i]>maxv2){
            maxv2=siz[i];
            pos2=i;
        }
     }
  }
  merge(find(pos1),find(pos2));
  LL ans=0;
  for(LL i=1;i<=n;i++){
    if(fa[i]==i){
        ans+=siz[i]*siz[i];
    }
  }
  cout<<ans<<"\n";
return 0;
}
